package com.destiny.filter;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class CrossFilter implements Filter {

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
    log.info("初始化跨域过滤器...");
  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    // 允许所有的请求域名访问我们的跨域资源，可以固定单个或者多个内容, 但是必须写上协议、主机和端口号，例如http://localhost:8080
    httpResponse.setHeader("Access-Control-Allow-Origin", "*");

    // 允许何种请求方法访问该跨域资源服务器
    httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");

    // 预检请求的有效期，单位为秒。有效期内，不会重复发送预检请求
    httpResponse.setHeader("Access-Control-Max-Age", "3600");

    // 允许所有的请求header访问，可以自定义设置任意请求头信息
    httpResponse.addHeader("Access-Control-Allow-Headers",
        "token, Accept, Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With");

    // 是否允许用户发送、处理cookie
    httpResponse.setHeader("Access-Control-Allow-Credentials", "true");

    // 允许跨域请求中拿到响应头的token
    httpResponse.setHeader("Access-Control-Expose-Headers", "token, sessionId");
    chain.doFilter(request, httpResponse);
  }

  @Override
  public void destroy() {

  }
}
